package com.agrimall.servlet;

import com.agrimall.entity.Banner;
import com.agrimall.service.BannerService;
import com.agrimall.service.impl.BannerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Banner列表Ajax Servlet
 */
@WebServlet("/banner/list")
public class BannerListServlet extends HttpServlet {
    private BannerService bannerService = new BannerServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            // 查询启用的Banner列表
            List<Banner> banners = bannerService.getVisibleBanners();
            
            // 构建JSON响应
            StringBuilder json = new StringBuilder("{\"success\":true,\"data\":[");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            
            for (int i = 0; i < banners.size(); i++) {
                Banner banner = banners.get(i);
                if (i > 0) json.append(",");
                json.append("{");
                json.append("\"bannerId\":").append(banner.getBannerId()).append(",");
                // 处理图片URL：如果以/开头但不是完整URL，则添加contextPath
                String imageUrl = banner.getImageUrl();
                if (imageUrl != null) {
                    if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
                        // 完整URL，直接使用
                    } else if (imageUrl.startsWith("/") && !imageUrl.startsWith(request.getContextPath())) {
                        // 以/开头的路径（如 /upload/xxx.png），需要加上contextPath
                        imageUrl = request.getContextPath() + imageUrl;
                    } else if (!imageUrl.startsWith("/")) {
                        // 相对路径，加上contextPath和/
                        imageUrl = request.getContextPath() + "/" + imageUrl;
                    }
                }
                json.append("\"imageUrl\":\"").append(escapeJson(imageUrl != null ? imageUrl : "")).append("\",");
                json.append("\"title\":\"").append(escapeJson(banner.getTitle() != null ? banner.getTitle() : "")).append("\",");
                json.append("\"description\":\"").append(escapeJson(banner.getDescription() != null ? banner.getDescription() : "")).append("\",");
                json.append("\"sortOrder\":").append(banner.getSortOrder()).append(",");
                json.append("\"createTime\":\"").append(banner.getCreateTime() != null ? sdf.format(banner.getCreateTime()) : "").append("\"");
                json.append("}");
            }
            json.append("]}");
            
            out.print(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"获取Banner列表失败\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 转义JSON字符串
     */
    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }
}

